package com.mpsc.api.unit;

import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class ListUtils {

    /**
     * 将集合分割为指定大小的集合
     *
     * @param list 原始数据结合
     * @param size 分隔后各个集合大小
     * @return list
     */
    public static <T> List<List<T>> splitList(List<T> list, int size) {
        List<List<T>> resultList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            List<T> result = new ArrayList<>();
            for (int i = 0, len = list.size() - 1; i <= len; i++) {
                result.add(list.get(i));
                if (result.size() == size && i != len) {
                    resultList.add(result);
                    result = new ArrayList<>();
                }
                if (i == len) {
                    resultList.add(result);
                }
            }
        }
        return resultList;
    }

    /**
     * 平均拆分list方法.
     *
     * @param source 被拆分的集合
     * @param n      拆分为集合个数
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> averageAssign(List<T> source, int n) {
        List<List<T>> result = new ArrayList<List<T>>();
        int remaider = source.size() % n;
        int number = source.size() / n;
        int offset = 0;//偏移量
        for (int i = 0; i < n; i++) {
            List<T> value = null;
            if (remaider > 0) {
                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remaider--;
                offset++;
            } else {
                value = source.subList(i * number + offset, (i + 1) * number + offset);
            }
            result.add(value);
        }
        return result;
    }
}
